import { View } from "@tarojs/components";

import "./ByTabs.less";
import ByText from "./ByText";

type TabItemProps = {
  source: {
    label: string;
    value?: string | number;
    [key: string]: any;
  };
  checked?: boolean;
  capsule?: boolean;
  onClick?: () => void;
};

type ByTabsProps = {
  tabs: {
    label: string;
    value?: string | number;
    [key: string]: any;
  }[];
  /**
   * 当前选中项
   */
  active?: string | number;
  /**
   * 是否为胶囊按钮
   */
  capsule?: boolean;
  className?: string;

  content?: "around" | "start";

  onChange?: (active: any, tab: TabItemProps["source"]) => void;
};

const TabItem = ({ source, checked, capsule, onClick }: TabItemProps) => {
  return (
    <View
      className={`h-[62px] px-2 flex-center by-tab-item ounded-full ${
        capsule && "capsule"
      } ${checked && "checked"}`}
      onClick={onClick}
      style={{ cursor: "pointer" }}
    >
      <ByText
        truncated
        className={`relative ${
          checked ? (capsule ? "text-white" : "") : "text-second"
        }`}
      >
        {source.label}
      </ByText>
    </View>
  );
};

export default ({
  tabs,
  active,
  content = "around",
  capsule,
  onChange,
  className,
}: ByTabsProps) => {
  return (
    <View
      className={`flex 
        ${content === "around" ? "justify-around" : "justify-start"}
        ${capsule ? "bg-page rounded-full" : ""}
        ${className}
      `}
    >
      {tabs.map((item, index) => (
        <TabItem
          source={item}
          key={index}
          capsule={capsule}
          checked={(item.value ?? index) === active}
          onClick={() => onChange?.(item.value ?? index, item)}
        />
      ))}
    </View>
  );
};
